package com.touni.lambda.diycollectors;

import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;

import static java.util.stream.Collector.Characteristics.IDENTITY_FINISH;
import static java.util.stream.Collector.Characteristics.UNORDERED;

/**
 * @ClassName : ComplexCollector
 * @Description :
 * @Author : lwq
 * @Date: 2020-11-23 09:54
 */                                          //流中元素类型  累加部分   collect最终类型
public class ComplexCollector<T> implements Collector<T, Set<T>, Map<String,T>> {

    @Override //结果容器
    public Supplier<Set<T>> supplier() {
        return HashSet::new;
    }

    @Override //将当前元素装入结果容器
    public BiConsumer<Set<T>, T> accumulator() {
        return (set,t) -> set.add(t);
    }

    @Override //合并多个结果容器
    public BinaryOperator<Set<T>> combiner() {
        return (set1,set2) -> {
            set1.addAll(set2);
            return set1;
        };
    }

    @Override //对结果容器的最终转换
    public Function<Set<T>, Map<String, T>> finisher() {
       return  set -> {
            Map<String,T> map = new HashMap<>();
            set.forEach(t -> map.put(t.toString(),t));
            return map;
        };
    }

    @Override
    public Set<Characteristics> characteristics() {
        return Collections.unmodifiableSet(EnumSet.of(IDENTITY_FINISH,UNORDERED));
    }
}
